package com.unibuy.smartdevice.ui;

import android.content.Context;
import android.os.Bundle;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.unibuy.smartdevice.AppCompatActivityAbstract;
import com.unibuy.smartdevice.MyApp;
import com.unibuy.smartdevice.database.SettinglogsDao;
import com.unibuy.smartdevice.databinding.ActivitySettingBinding;
import com.unibuy.smartdevice.exception.LogsParseException;
import com.unibuy.smartdevice.exception.LogsSettingEmptyException;
import com.unibuy.smartdevice.external.HttpAPI;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.tools.HandlerMainSchedulerOnClick;
import com.unibuy.smartdevice.tools.ToastHandlerMain;
import com.unibuy.smartdevice.tools.Tools;
import com.unibuy.smartdevice.ui.recycler.RecyclerSettingListAdpter;
import com.unibuy.smartdevice.utils.LanguageHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SettingActivity extends AppCompatActivityAbstract {
    public enum Option {
        TOAST(0),
        CHECK_AND_SAVE_STATUS(1),
        DATA_RELOAD(2),
        ;

        private int option;

        public int getOption() {
            return option;
        }

        Option(int option) {
            this.option = option;
        }
    }

    public static final Map<Integer, Option> optionMap = new HashMap<>();
    static {
        for (Option option : Option.values()) {
            optionMap.put(option.getOption(), option);
        }
    }

    @Override
    protected Context setCtx() {
        return this;
    }

    @Override
    protected Class<?> setCls() {
        return getClass();
    }

    @Override
    protected HandlerMain setHandlerMain() {
        return new ToastHandlerMain(getCtx(), getLogs()) {
            @Override
            protected void execute(Context context, int commandCode, String message) {
                Option option = optionMap.get(commandCode);

                switch (option) {
                    case TOAST:
                            super.execute(context, commandCode, message);
                        break;
                    case CHECK_AND_SAVE_STATUS:
                            super.execute(context, commandCode, message);
                            binding.buttonBack.setVisibility(View.VISIBLE);
                            checkSetting();
                            saveStatusList(context);
                        break;
                    case DATA_RELOAD:
                        binding.buttonBack.setVisibility(View.INVISIBLE);
                        MyApp.getInstance().getMachine().setMachineID(binding.editMachineID.getText().toString());

                        try {
                            httpAPI.downloadSetting();
                        } catch (LogsParseException | LogsSettingEmptyException e) {
//                            exception(context, e.getErrorCode(), e.getLocalizedMessage());
                            getLogs().warning(e);
                        }
                        break;
                }
            }
        };
    }

    private ActivitySettingBinding binding;
    private List<String> statusList = new ArrayList<>();
    private RecyclerSettingListAdpter recyclerSettingListAdpter;
    private HttpAPI httpAPI;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 讀取最後設定語言的設定
        LanguageHelper.applySavedLanguage(this);
        binding = ActivitySettingBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        httpAPI = new HttpAPI(getHandlerMain());

        recyclerSettingListAdpter = new RecyclerSettingListAdpter(statusList);
        binding.recyclerSettingList.setAdapter(recyclerSettingListAdpter);
        binding.recyclerSettingList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        MyApp.getInstance().initialSettingData();

        if (!MyApp.getInstance().getMachine().getMachineID().isEmpty()) {
            binding.editMachineID.setText(MyApp.getInstance().getMachine().getMachineID());
            binding.buttonReload.setText("重新綁定");
        }

        if (statusList.isEmpty()) {
            SettinglogsDao settinglogsDao = new SettinglogsDao(this);
            for (String data: settinglogsDao.getAll()) {
                statusList.add(data);
            }
        }

        if (!statusList.isEmpty()) {
            recyclerSettingListAdpter.notifyItemInserted(statusList.size() -1);
        }

        binding.buttonBack.setOnClickListener(v -> {
            MyApp.updateLog(getCtx());
            finish();
        });

        binding.buttonReload.setOnClickListener(v -> {
            if (binding.editMachineID.getText().length() <= 0) {
                getHandlerMain().start(getClass().getSimpleName(), "@機器序號未輸入");
                return;
            }

            getHandlerMain().start("ButtonReloadOnClick", Option.DATA_RELOAD.getOption(), "data reload");
        });

        getTools().setImmHideByFocusChange(binding.editMachineID);
        binding.editMachineID.clearFocus();
    }

    public void saveStatusList(Context context) {
        SettinglogsDao settinglogsDao = new SettinglogsDao(context);
        settinglogsDao.deleteAll();
        settinglogsDao.insertAll(statusList);
        settinglogsDao.close();
    }

    private void checkSetting() {
        int size = statusList.size();
        statusList.clear();
        recyclerSettingListAdpter.notifyItemRangeRemoved(0, size);

        if (!MyApp.getInstance().getMachine().getMachineID().isEmpty()) {
            statusList.add("download maching data:"
                + MyApp.getInstance().getMachine().getMachineID()
                +"/"
                +Tools.randomReplace(MyApp.getInstance().getMachine().getApiKey(), 0.3)
            );
        }

        if (MyApp.getInstance().getGreenInvoice().getGreenMerchantID() != null) {
            statusList.add("download greenpay Invoice data:"
                    +Tools.randomReplace(String.valueOf(MyApp.getInstance().getGreenInvoice().getGreenMerchantID()), 0.3)
                    +"/"
                    +Tools.randomReplace(String.valueOf(MyApp.getInstance().getGreenInvoice().getGreenHashKey()), 0.3)
                    +"/"
                    +Tools.randomReplace(String.valueOf(MyApp.getInstance().getGreenInvoice().getGreenHashIV()), 0.3)
                    +"/"
                    +Tools.randomReplace(String.valueOf(MyApp.getInstance().getGreenInvoice().getGreenEmail()), 0.3)
            );
        }

        if (!MyApp.getInstance().getEsunpay().getStoreID().isEmpty()) {
            statusList.add("download esunpay data:"
                +Tools.randomReplace(MyApp.getInstance().getEsunpay().getStoreID(), 0.3)
                +"/"
                +Tools.randomReplace(MyApp.getInstance().getEsunpay().getTermID(), 0.3)
                +"/"
                +Tools.randomReplace(MyApp.getInstance().getEsunpay().getHash(), 0.3)
            );
        }

        if (MyApp.getInstance().getGreenpaySetting().getAppKey() != null && !MyApp.getInstance().getGreenpaySetting().getAppKey().isEmpty()) {
            statusList.add("download greenpay data:"
                    +Tools.randomReplace(String.valueOf(MyApp.getInstance().getGreenpaySetting().getAppId()), 0.3)
                    +"/"
                    +Tools.randomReplace(MyApp.getInstance().getGreenpaySetting().getAppKey(), 0.3)
                    +"/"
                    +Tools.randomReplace(MyApp.getInstance().getGreenpaySetting().getPartnerKey(), 0.3)
            );

            statusList.add("download greenpay merchant data:"
                    +Tools.randomReplace(String.valueOf(MyApp.getInstance().getGreenpayMerchant().getLineMerchantId()), 0.3)
                    +"/"
                    +Tools.randomReplace(MyApp.getInstance().getGreenpayMerchant().getPsMerchantId(), 0.3)
                    +"/"
                    +Tools.randomReplace(MyApp.getInstance().getGreenpayMerchant().getEasyMerchantId(), 0.3)
                    +"/"
                    +Tools.randomReplace(MyApp.getInstance().getGreenpayMerchant().getPiMerchantId(), 0.3)
                    +"/"
                    +Tools.randomReplace(MyApp.getInstance().getGreenpayMerchant().getJkoMerchantId(), 0.3)
            );
        }

        if (!MyApp.getInstance().getProductList().isEmpty()) {
            size = MyApp.getInstance().getProductList().size();
            statusList.add("download product data:" + size);
        }

        if (!MyApp.getInstance().getFontendAdUrlString().isEmpty()) {
            size = MyApp.getInstance().getFontendAdUrlString().size();
            statusList.add("download ad url data:" + size);
        }

        recyclerSettingListAdpter.notifyItemInserted(statusList.size() -1);
    }
}